package com.example.librarymanagementsystembackend.usermanagement.service;

import com.example.librarymanagementsystembackend.usermanagement.entity.*;
import com.example.librarymanagementsystembackend.usermanagement.mapper.UserMapper;
import com.example.librarymanagementsystembackend.utils.InvalidRequestException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;


@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    UserActionService userActionService;

    /**
     * 密码加密服务
     */
    private BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    /**
     * 获取用户信息 通过 ID
     */
    public User getUserById(int id) {
        User user = userMapper.findUserById(id);
        if (user == null) {
            throw new InvalidRequestException(404, "用户不存在");
        }
        return user;
    }

    /**
     * 获取全部用户
     *
     * @return 所有用户列表
     */
    public List<User> findAllUsers() {
        return userMapper.findAllUsers();
    }

    /**
     * 用户注册
     *
     * @param dto
     */
    @Transactional
    public void userRegister(UserRegisterDTO dto) {
        // 验证两次密码是否一致
        if (!dto.getPassword().equals(dto.getConfirmPassword())) {
            throw new InvalidRequestException("两次输入的密码不一致");
        }

        // 检查用户名是否已存在
        if (userMapper.existsByUsername(dto.getUsername())) {
            throw new InvalidRequestException("用户名已被使用");
        }

        // 创建用户实体
        User user = new User();
        user.setUsername(dto.getUsername());
        user.setPassword(passwordEncoder.encode(dto.getPassword())); // 加密密码
        user.setIsAdmin(false); // 默认非管理员

        // 插入用户
        userMapper.insertUser(user);
        Integer userID = user.getId(); // 插入用户后自动返回的当前ID
        // System.out.println("userID = " + userID);

        // 创建默认用户资料
        UserProfile profile = new UserProfile();
        profile.setAvatarUrl("default_avatar.jpg");
        profile.setBackgroundColor("#FFFFFF");
        // 插入默认资料
        userMapper.insertUserProfile(user.getId(), profile.getAvatarUrl(), profile.getBackgroundColor());
    }

    /**
     * 更新用户资料 通过 ID
     *
     * @param userId 用户ID
     * @param dto    用户信息DTO
     */
    public void updateUserProfile(Integer userId, UserProfileDTO dto) {
        userMapper.updateUserProfile(
                userId,
                dto.getAvatarUrl(),
                dto.getBackgroundColor()
        );
    }

    /**
     * 删除用户 通过 ID
     *
     * @param id 用户 ID
     */
    @Transactional
    public void deleteUserById(Integer id) {
        User user = userMapper.findUserById(id);
        if (user == null) {
            throw new InvalidRequestException("没有找到用户ID:" + id);
        }

        // 先删除关联的profile
        userMapper.deleteProfileByUserId(id);
        // 再删除用户
        userMapper.deleteUserById(id);
    }

    /**
     * 查询用户扩展信息 通过 ID
     */
    public UserProfile findProfileByUserId(Integer id) {
        UserProfile profile = userMapper.findProfileByUserId(id);
        if (profile == null) {
            throw new InvalidRequestException("没有找到用户ID:" + id);
        }
        return profile;
    }


    public User login(LoginInfo loginInfo) {
        String username = loginInfo.getUsername();
        String rawPassword = loginInfo.getPassword();

        // 1. 查找用户（避免两次查询）
        User user = userMapper.getUserByUsername(username);
        if (user == null) {
            return null;
        }

        // 2. 验证密码
        if (!passwordEncoder.matches(rawPassword, user.getPassword())) {
            return null;
        }

        // 3. 创建并保存用户操作日志（可以异步处理以提升性能）
        try {
            UserAction userAction = new UserAction();
            userAction.setUserId(user.getId());
            userAction.setActionTime(LocalDateTime.now());
            userAction.setActionContent("用户登录了系统");
            userActionService.createUserAction(userAction);
        } catch (Exception e) {
            // 日志记录失败时可以选择记录异常，但不影响主流程
            // logger.warn("Failed to create user action log", e);
        }

        return user;
    }
}
